package com.tm.controller;

import com.tm.enums.ResultEnum;
import com.tm.pojo.LoginPojo;
import com.tm.result.Result;
import com.tm.service.LoginService;
import com.tm.utils.SendSmsUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author wangSang
 * @create 2022-09-14 13:41
 */
@RestController
@RequestMapping("login")
public class LoginController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LoginService loginService;
    // 发送短信接口
    @PostMapping("sendSms")
    public Result  SendSms(@RequestBody String phoneNumber){

        String s = SendSmsUtil.SendSms(phoneNumber);
        redisTemplate.opsForValue().set("user_"+phoneNumber,s,5000l,TimeUnit.SECONDS);
        return Result.ZDY(ResultEnum.SENDSMS_SUCCESS);
    }


    //验证等录
    @PostMapping("login")
    public Result logon(@RequestBody LoginPojo loginPojo){
        //判断是那种方法进行等率
        if(StringUtils.isNotBlank(loginPojo.getUserPwd()) && StringUtils.isNotBlank(loginPojo.getUserName()) ){
            //根据用户名进行查询
            LoginPojo user  = loginService.queryLogin(loginPojo.getUserName());
            //判断是否有该用户
            if(user == null){

                return Result.ZDY(ResultEnum.LOGON_ERROR);
            }
            //判断密码是否正确
            if(user.getUserPwd().equals(loginPojo.getUserPwd())){
                String token = UUID.randomUUID().toString().replace("-", "");
                redisTemplate.opsForValue().set("token_"+user.getPhoneNumber(),token);
                return Result.LOGON_SUCCESS(token);
            }else {

                return Result.ZDY(ResultEnum.LOGON_ERROR);
            }

        }

        //判断是那种方法进行等率
        if(StringUtils.isNotBlank(loginPojo.getPhoneNumber()) && StringUtils.isNotBlank(loginPojo.getUserCode()) ){
            //根据用户手机号取出验证码
            String o = (String)redisTemplate.opsForValue().get("user_" + loginPojo.getPhoneNumber());
            //判断验证码是否过期
            if(o == null){

                return Result.ZDY(ResultEnum.OVERDUE_ERROR);
            }
            //判断验证码是否一致
            if(loginPojo.getUserCode().equals(o)){

                String token = UUID.randomUUID().toString().replace("-", "");
                redisTemplate.opsForValue().set("token_"+ loginPojo.getPhoneNumber(),token);
                return Result.LOGON_SUCCESS(token);
            }

                return Result.ZDY(ResultEnum.SENDSMS_ERROR);
        }


       return Result.ERROR(ResultEnum.NETWORK_ERROR);
    }


    @PostMapping("quit")
    public Result  quit(@RequestBody String phoneNumber){

        Boolean delete = redisTemplate.delete("token_"+phoneNumber);

        return Result.ZDY(ResultEnum.QUIT_SUCCESS);
    }
}
